﻿using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading;

public class UDPRemote : Remote,ISocketServer
{
    protected UDPSocketServer UDPSocketServer => m_SocketServer as UDPSocketServer;

    public Action<IPEndPoint> onDisconnect;

    int m_Port;
    public int listenPort => m_Port;
    //public override bool connected => true;

    public UDPRemote(long clientId, IPEndPoint ipEndPoint,UDPSocketServer uDPSocketServer) : base(clientId ,ipEndPoint, uDPSocketServer)
    {
        uDPSocketServer.SetSocketServerHandler(this);
    }
    
    public void BeginReceive(int port)
    {
        m_Port = port;

        UDPSocketServer.Start(port, 5);

        UDPSocketServer.BeginReceive();

        GameDebug.Log($"UDP Remote target client:{this.ipEndPoint} 开始接收数据");
    }

    public override string ToString()
    {
        return $"clientId:{clientId}  ip:{this.m_EndPoint} ";
    }

    public virtual void OnReceiveData(byte[] data)
    {
        this.OnProcessMessageData(data);
    }

    public void OnReceiveData(EndPoint endPoint, byte[] data)
    {
        m_EndPoint = (IPEndPoint)endPoint;

        //GameDebug.Log($"收到 endPoint:{endPoint}  数据：{data.Length}");
        this.OnReceiveData(data);
    }

    public void OnRecOrSendFailed(EndPoint endPoint)
    {
        GameDebug.Log($"UDP Remote OnRecOrSendFailed :{endPoint}  this.ip:{this.ipEndPoint}");

        onDisconnect?.Invoke(this.ipEndPoint);// ((IPEndPoint)endPoint);
    }

    public void Release()
    {
        m_SocketServer.Release();
        m_SocketServer = null;
    }
}


